package other;

import util.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: javase
 * @description:
 * @author: lld
 * @create: 2021-06-08 19:46
 **/
public class SumRoot129 {
    List<String> list = new ArrayList<>();

    public int sumNumbers(TreeNode root) {
        dfs(root, new StringBuilder());
        int sum = 0;
        for (String s : list) {
            sum += Integer.parseInt(s);
        }
        return sum;
    }

    public void dfs(TreeNode root, StringBuilder sb) {
        if (root == null) return;
        sb.append(String.valueOf(root.val));
        if (root.left == null && root.right == null) {
            list.add(sb.toString());
            // sb.deleteCharAt(sb.length()-1);
            // return;
        }
        dfs(root.left, sb);
        dfs(root.right, sb);
        // 回溯
        sb.deleteCharAt(sb.length() - 1);
    }

    public static void main(String[] args) {
        SumRoot129 sumRoot129 = new SumRoot129();
        int i = sumRoot129.sumNumbers(TreeNode.build());
        System.out.println(i);
//        124 125 13=262
    }
}